package com.bjsxt.hibernate;

import java.lang.reflect.Method;
import java.sql.DriverManager;
import java.util.HashMap;

import org.apache.commons.collections.map.HashedMap;
import org.omg.CORBA.PUBLIC_MEMBER;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.sun.javafx.collections.MappingChange.Map;
import com.sun.jndi.url.corbaname.corbanameURLContextFactory;

public class Session {

		String tableName = "_student";
		HashMap<String, String> cfg = new HashMap<String,String>();
		
		String[] methodNames;
	
	
	public Session(){
		
		cfg.put("_id", "id");
		cfg.put("_name", "name");
		cfg.put("_age", "age");
		
		methodNames = new String[cfg.size()];
		
	}
	
	public void save(Student student) throws Exception{
		String sql = createSql();
		
		Class.forName("com.mysql.jdbc.Driver");
		java.sql.Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/hibernate","root","sasa");
		PreparedStatement ps = (PreparedStatement) connection.prepareStatement(sql);
		
/*		for(String m:methodNames){
			System.out.print(m);
		}*/
		
		for(int i=0;i<methodNames.length;i++){
			Method m = student.getClass().getMethod(methodNames[i]);
			Class r =m.getReturnType();
			if(r.getName().equals("java.lang.String")){
				
				String returnValue =(String) m.invoke(student);
				ps.setString(i+1, returnValue);
			}
			if(r.getName().equals("int")){
				
				Integer returnValue =(Integer) m.invoke(student);
				ps.setInt(i+1, returnValue);
			}
		}
		
		ps.executeUpdate();
		ps.close();
		connection.close();
	} 
	
	public String createSql(){
		
		String str1 = "";
		
		int index =0;		
		for(String string : cfg.keySet()){
			String v = cfg.get(string);
			v = Character.toUpperCase(v.charAt(0)) + v.substring(1);
			methodNames[index] = "get" +v;
			
			
			
			str1 += string +",";	
			index++;
		}
		str1 = str1.substring(0,str1.length()-1);
		
		//System.out.print(str1);
		
		String str2 = "";
		for(int i=0;i<cfg.size();i++)
		{
			str2 = str2 + "?,";
		}
		str2 = str2.substring(0,str2.length()-1);
		//System.out.print(str2);
		
		String sql = "insert into" +" "+ tableName + "(" + str1 + ")" + "values (" + str2 + ")";
		System.out.print(sql);
		return sql;				
	}
}
